﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GrayParrot.Core
{
    /// <summary>
    /// Cancellable Tasks Manager class
    /// </summary>
    /// <remarks>
    /// Manage the task list for easy tasks cancellation disposing the istance running on task...
    /// </remarks>
    /// <typeparam name="T"></typeparam>
    public class CancellableTasksManager<T> where T : class, new()
    {
        List<T> m_coda = null;

        /// <summary>
        /// Initializes a new instance of the <see cref="CancellableTasksManager{T}"/> class.
        /// </summary>
        public CancellableTasksManager()
        {
            m_coda = new List<T>();
        }

        /// <summary>
        /// Factory method to create a {T} new instance and add it to the instances list...
        /// </summary>
        /// <returns></returns>
        public T Create()
        {
            T retValue = new T();

            AddInstance(retValue);

            return retValue;
        }

        /// <summary>
        /// Manually Adds the instance to the instances list...
        /// </summary>
        /// <param name="instance">The instance.</param>
        public void AddInstance(T instance)
        {
            m_coda.Add(instance);
        }

        /// <summary>
        /// Dispose the instances and finally clear the list of instances...
        /// </summary>
        /// <param name="action">The action.</param>
        public void DisposeInstances(Action<T> action)
        {
            for (int i = 0; i < m_coda.Count(); i++)
            {
                action(m_coda[i]);
            }

            m_coda.Clear();
        }
    }
}
